package loginServlet;

import java.io.IOException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sessions.LoginSystemRemote;
import sessions.UpdateProfileRemote;

public class NewUserServlet extends HttpServlet {

	private static final long serialVersionUID = -3867365856174819553L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		insertNewUser(request, response);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		insertNewUser(request, response);
	}

	private void insertNewUser(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = 0;
		try {
			Context jndiCtx = new InitialContext();
			LoginSystemRemote loginSystemRemote = (LoginSystemRemote) jndiCtx
					.lookup("Progetto/LoginSystem/remote");
			UpdateProfileRemote upr = (UpdateProfileRemote) jndiCtx
					.lookup("Progetto/UpdateProfile/remote");
			if (!upr.isPresent(request.getParameter("email"))) {
				//se la email inserita non e' gia' usata
				id = loginSystemRemote.insertUser(
						request.getParameter("email"),
						request.getParameter("nome"),
						request.getParameter("cognome"),
						request.getParameter("password"),
						request.getParameter("data"),
						request.getParameter("numTel"),
						request.getParameter("numCel"));
				request.getSession().setAttribute("id", id);
				request.getSession().setAttribute("nome",
						request.getParameter("nome"));
				request.getSession().setAttribute("cognome",
						request.getParameter("cognome"));
				request.getSession().setAttribute("type", "utente");
				response.sendRedirect("/ProgettoWeb/Login/UserRegistrated.jsp");
			}else{
				request.getSession().setAttribute("error", "mail");
				response.sendRedirect("/ProgettoWeb/Login/UserRegistration.jsp");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Errore nella servlet");
		}
	}
}
